<template>
  <a-card>
    <a-row>
      <a-col :span="8">
        <div style="position:relative;top:0;left:20px;">
          <a-input-search
            v-model="searchValue"
            style="margin-bottom: 8px;width: 70%"
            placeholder="搜索"
            @change="searchTreeNode"
          />
        </div>
        <div style="height: 700px;overflow-y: scroll;margin: 0px 10px;">
          <a-spin tip="加载中..." :spinning="treeSpinning">
            <a-tree
              v-if="treeData"
              :tree-data="treeData"
              :replaceFields="{ children: 'children', title: 'name',key: 'id' }"
              @select="onSelect"
            >
            </a-tree>
          </a-spin>
        </div>
      </a-col>
      <a-col :span="16">
        <div class="table-page-search-wrapper" style="margin: 0px 10px;">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item label="姓名">
                  <a-input placeholder="请输入姓名" v-model="queryParam.f_username" />
                </a-form-item>

              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="电话">
                  <a-input placeholder="请输入电话" v-model="queryParam.f_mobile" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <div style="text-align: right">
                  <span
                    class="table-page-search-submitButtons"
                    :style="( { float: 'right', overflow: 'hidden' }) || {}"
                  >
                    <a-button type="primary" class="btn_primary_color" @click="queryUser" icon="search">查询</a-button>
                    <a-button icon="reload" class="btn_normal_color" style="margin-left: 8px"
                              @click="reQuery">重置</a-button>
                  </span>
                </div>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-row>
          <a-col :md="8" :sm="24" />
          <a-col :md="8" :sm="24" />
          <a-col :md="8" :sm="24">
            <div style="text-align: right;margin: 10px 10px">
              <a-button
                type="primary"
                :disabled=" Object.keys(this.selectedNode).length === 0 || this.selectedNode.level!=='2'"
                class="m-l-8 btn_primary_color"
                @click="addHandleData"
                icon="plus">新增人员
              </a-button>
            </div>

          </a-col>
        </a-row>
        <div v-show="showTable">
        <a-spin tip="加载中..." :spinning="spinning2">
          <a-table
            :scroll="{x: 550, y: 550 }"
            v-if="listData"
            :columns="ucolumns"
            :data-source="listData"
            :pagination="upagination"
            @change="tableChange"
            rowKey="id"
            size="middle"
            ref="table"
            :bordered="ubordered"
          >
            <span slot="serial" slot-scope="text, record, index">
              {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
            </span>

            <div slot="orgnameSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
              <a-tooltip placement="topLeft">
                <template slot="title">
                  <span>{{ record.orgname }}</span>
                </template>
                {{ record.orgname }}
              </a-tooltip>
            </div>

            <div slot="addressSlot" slot-scope="text, record" class="beyond_hiding" style="width: 100%">
              <a-tooltip placement="topLeft">
                <template slot="title">
                  <span>{{ record.address }}</span>
                </template>
                {{ record.address }}
              </a-tooltip>
            </div>

            <template slot="operation" slot-scope="text, record">
              <a href="javascript:;" @click="editTarget(record)">编辑</a>
              <a-divider type="vertical"></a-divider>
              <a-popconfirm
                title="确定删除吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="removeUser(record)"
              >
                <a href="javascript:;" type="link">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-spin>
        </div>
      </a-col>
    </a-row>
    <a-drawer
      title="人员编辑"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
      destroyOnClose
    >
      <TargetOrgEdit v-if="visible" ref="viewAdd" @close="onClose"></TargetOrgEdit>
    </a-drawer>
  </a-card>
</template>

<script>
import { tree as admUnitTree } from '@/api/std/std_admunit'
import { deleteStd_admuser, listDetail } from '@/api/std/std_admuser'
import { queryUserByMobile } from '@/api/ding/di_rel_dept_correct'
import TargetOrgEdit from '@/views/base/TargetOrgEdit.vue'

const ucolumns = [
  {
    title: '序号',
    width: 50,
    key: 'index',
    align: 'center',
    fixed: 'left',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '名称',
    dataIndex: 'username',
    key: 'username',
    align: 'center',
    width: 150
  },
  {
    title: '联系号码',
    dataIndex: 'mobile',
    key: 'mobile',
    align: 'center',
    width: 200
  },
  {
    title: '组织机构',
    dataIndex: 'orgname',
    key: 'orgname',
    align: 'left',
    width: 250,
    scopedSlots: { customRender: 'orgnameSlot' }
  },
  {
    title: '联系地址',
    dataIndex: 'address',
    key: 'address',
    align: 'left',
    width: 350,
    scopedSlots: { customRender: 'addressSlot' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 120,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  }
]
export default {
  components: { TargetOrgEdit },
  data () {
    return {
      showTable:false,
      treeSpinning: false, // unit树是否展开
      treeData: [], // 树数据
      cloneTreeData: [], // 备份树节点数据
      ucolumns: ucolumns,
      listData: [], // 列表数据
      visible: false, // 显示侧边栏
      selectedNode: {level:'0'}, // 选中的节点
      queryParam: {
        f_username: '',
        f_mobile: '',
        f_admunitid: '',
        pageNumber: 1,
        pageSize: 20
      },
      spinning2: false,
      ubordered: true, // 是否显示线条
      // 测试
      searchValue: undefined, // 搜索值
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
    }
  },
  async created () {
    const a = Date.now()
    this.treeSpinning = true
    this.spinning2 = true

    admUnitTree().then(res => {
      if (res.code == 0) {
        this.treeData = res.data
        this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
        const b = Date.now()
        if (b - a < 500) {
          setTimeout(() => {
            this.treeSpinning = false
          }, 500)
        } else {
          this.treeSpinning = false
        }
      }
    })
    // 查询人员
    this.queryUser()
  },
  methods: {

    searchTreeNode () {
      const value = this.searchValue
      this.filter(this.treeData, value)
      if (value == '') {
        this.treeData = JSON.parse(JSON.stringify(this.cloneTreeData)) // cloneTreeData 接口返回深拷贝的数据
      }
    },
    filter (nodes, query) {
      // 条件就是节点的title过滤关键字
      const predicate = function (node) {
        if (node.name.indexOf(query) > -1) {
          return true
        } else {
          return false
        }
      }
      if (!(nodes && nodes.length)) {
        return []
      }
      const newChildren = []
      for (const node of nodes) {
        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        if (predicate(node)) {
          newChildren.push(node)
          node.children = this.filter(node.children, query)
        } else {
          newChildren.push(...this.filter(node.children, query))
        }
      }
      this.treeData = newChildren // this.treeData接口返回的数组
      return newChildren.length ? newChildren : []
    },

    // 点击树节点事件
    onSelect (ks, data) {
      if (data.selectedNodes && data.selectedNodes.length > 0) {
        // 封装数据
        this.selectedNode.id = data.selectedNodes[0].data.props.id
        this.selectedNode.name = data.selectedNodes[0].data.props.name
        this.selectedNode.typeid = data.selectedNodes[0].data.props.typeid
        const selectedNode = this.selectedNode
        console.log(selectedNode)
        // 设置节点层级
        if (this.selectedNode.typeid && this.selectedNode.typeid !== '0') {
          this.selectedNode.level = '2'
          this.queryParam.f_admunitid = this.selectedNode.id
          this.queryParam.pageNumber='1'
          this.queryUser()
          this.showTable = true
        } else {
          this.showTable = false
          this.selectedNode.level = '1'
          this.queryParam.f_admunitid = ''
          this.queryParam.pageNumber='1'
          this.listData = []
        }
      } else {
        this.showTable = false
        this.selectedNode = {}
        this.queryParam.f_admunitid = ''
        this.queryParam.pageNumber='1'
        this.listData = []
      }
    },
    tableChange (pagination, filters, sorter, { currentDataSource }) {
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.queryUser()
    },
    // 查询关联用户列表
    queryUser () {
      this.showTable = true
      this.spinning2 = true
      const a = Date.now()
      listDetail(this.queryParam).then(res => {
        if (res.code === 0) {
          this.listData = res.data.records
          this.upagination.total = res.data.total
          this.upagination.current = res.data.current
          this.upagination.pageSize = res.data.size
          const b = Date.now()
          if (b - a < 250) {
            setTimeout(() => {
              this.spinning2 = false
            }, 250)
          } else {
            this.spinning2 = false
          }
        } else {
          this.spinning2 = false
          this.$message.error('查询失败')
        }
      })
    },
    // 刷新列表
    refreshList () {
      this.queryUser()
    },
    // 删除用户根据id
    removeUser (record) {
      deleteStd_admuser(record.id).then((res) => {
        if (res.code === 0) {
          this.$message.success('删除成功')
          this.refreshList()
        } else {
          this.$message.error('删除失败')
        }
      })
    },
    // 添加关联人员
    addHandleData () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.viewAdd.refreshNode(this.selectedNode)
      })
    },
    // 收回抽屉
    onClose () {
      this.visible = false
      this.refreshList()
    },
    // 重置
    reQuery () {
      this.showTable = true
      this.queryParam.username = ''
      this.queryParam.mobile = ''
      this.queryParam.f_admunitid=''
      this.queryUser()
    },
    // 编辑
    editTarget( record ){
      const userid = record.userid
      const mobile = record.mobile
      const username = record.username
      const address = record.address
      const orgname = record.orgname
      const id = record.id
      this.visible = true
      this.$nextTick(() => {
      this.$refs.viewAdd.refreshNode({userid,username,address,orgname,mobile,id})
      })
    }
  }
}
</script>

<style>

</style>
